package com.project.service.base.message;

import com.project.myBeans.ConfigParameters;
import com.project.service.base.ehcahe.EhcacheService;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.AlibabaAliqinFcSmsNumSendRequest;
import com.taobao.api.response.AlibabaAliqinFcSmsNumSendResponse;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Author: TAO
 * Date: 2016/6/30
 * Time: 15:15
 */
@Service
public class MessageServiceImpl  implements MessageService {
    @Autowired
    private EhcacheService captchaService;

    @Autowired
    private ConfigParameters configParameters;

    private Logger log= Logger.getLogger(getClass());

    @Override
    //阿里大鱼
    public TaobaoClient getTaobaoClient()  {
        TaobaoClient client = new DefaultTaobaoClient(configParameters.getAliDaYuServer(),
                configParameters.getAliDaYuAppKey(),
                configParameters.getAliDaYuSecret());
        return  client;
    }

    @Override
    //阿里大鱼
    public AlibabaAliqinFcSmsNumSendRequest getAlidayuRequest(String phone, String code, String product, Integer expireMinute, String smsSignName, String smsTemplate){
        AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
        req.setSmsType("normal");
        req.setSmsFreeSignName(smsSignName);
        req.setSmsParamString("{\"code\":\""+code+"\",\"product\":\""+product+"\",\"number\":\""+expireMinute+"\"}");
        req.setRecNum(phone);
        req.setSmsTemplateCode(smsTemplate);
        return  req;
    }

    @Override
    public boolean sendSmsCode(String phone, String code,String smsTemplate){ //视业务情况作调整
        try {
            Integer expireMinute= configParameters.getAliDaYuSmsExpireMinute();
            String smsSignName=configParameters.getAliDaYuSmsSignName(); //签名
            String product= configParameters.getAliDaYuProduct(); //产品名称

            //阿里大鱼
            TaobaoClient client = getTaobaoClient();
            AlibabaAliqinFcSmsNumSendRequest req = getAlidayuRequest(phone,code,product,expireMinute,smsSignName,smsTemplate);
            AlibabaAliqinFcSmsNumSendResponse rsp = client.execute(req);
            System.out.println(rsp.getBody());
        }catch (Exception e)
        {
            e.printStackTrace();
            return false;
        }
        //将短信验证码加入cache
        captchaService.addCaptcha(phone,code);

        return true;
    }

}
